package com.weiawei.Model;

import javax.swing.*;
import java.util.concurrent.TimeUnit;

public class TimeThread extends Thread {
    private final JLabel label;
    public long millisecond = 0;

    public TimeThread(JLabel label) {
        this.label = label;
    }

    /**
     * 时间线开始
     *
     * <p>记录对局总时长</p>
     */
    public void run() {
        long startTime = System.currentTimeMillis();    // 开始时间
        long currentTime;
        long time;
        do {
            currentTime = System.currentTimeMillis();   // 当前时间
            time = currentTime - startTime;             // 持续时间
            millisecond = time;                         // 记录当前持续时间
            label.setText(transFormat(time));           // 将时间格式化为字符串，放在标签上
        } while (!this.isInterrupted());
    }

    /**
     * 将微秒的格式转换为"%02d:%02d:%02d"的字符串形式
     *
     * @param milliseconds 对局时长的微秒形式
     */
    public static String transFormat(long milliseconds) {
        long hours = TimeUnit.MILLISECONDS.toHours(milliseconds);
        long minutes = TimeUnit.MILLISECONDS.toMinutes(milliseconds) - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(milliseconds));
        long seconds = TimeUnit.MILLISECONDS.toSeconds(milliseconds) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(milliseconds));
        return String.format("%02d:%02d:%02d", hours, minutes, seconds);
    }
}
